const { createToken, verifyPwd, encrypted } = require("../utils/jwt");
const { Login } = require("../model/common");
const dayjs = require("dayjs");

const common = {
  // 登录
  login: async (req, res) => {
    const { username, password } = req.body;
    if (!username || !password) {
      return res.json({
        code: -1,
        msg: "用户名或密码不能为空",
      });
    }
    try {
      const results = await Login.findOne({ where: { username: username } });
      const isPwd = await verifyPwd(password, results?.password || "");
      if (!results || !isPwd) {
        return res.json({
          code: -1,
          msg: "用户名或密码错误",
        });
      }
      let expires = dayjs().add(1, "d").format("YYYY/MM/DD HH:mm:ss");
      res.json({
        code: 1,
        msg: "登录成功",
        data: {
          id: results.id,
          username: results.username,
          nickname: results.nickname,
          avatar: results.avatar,
          create_time: results.create_time,
          accessToken: createToken(
            {
              id: results.id,
              username: results.username,
            },
            "1d"
          ), // 10s后token过期
          expires,
        },
      });
    } catch (err) {
      console.error("异常捕获：", err);
      return res.json({
        code: 500,
        message: "服务器错误",
      });
    }
  },
  // 注册
  register: async (req, res) => {
    let { username, password, nickname, avatar } = req.body;
    if (!username || !password || !nickname) {
      return res.json({
        code: 400,
        msg: "用户名、密码、昵称、头像不能为空",
      });
    }
    try {
      const [row] = await db.query("select id,username,nickname from users where username=? or nickname=?", [username, nickname]);
      console.log(row);

      if (row.length > 0) {
        return res.json({
          code: 400,
          msg: "用户名或昵称已存在",
        });
      }

      password = await encrypted(password);

      const sql = `insert into users (username,password,nickname,avatar) values (?,?,?,?)`;
      const [results, fields] = await db.query(sql, [username, password, nickname, avatar]);

      return res.json({
        code: 200,
        msg: "注册成功",
        data: results[0],
      });
    } catch (error) {
      console.error(error);

      return res.json({
        code: 400,
        msg: "注册失败",
      });
    }
  },
  // 更新用户信息
  updateUserInfo: async (req, res) => {
    console.log("更新用户信息");
    let { id, nickname, avatar } = req.body;
    id = "11";
    nickname = "11还好";
    if (!id || !nickname) {
      return res.json({
        code: 400,
        msg: "id、昵称、头像不能为空",
      });
    }
    const sql = `update users set nickname = ?,avatar = ? where id = ?`;
    const [results, fields] = await db.query(sql, [nickname, avatar, id]);
    console.log(results, fields);
  },
  // 文件上传
  uploadFile: async (req, res) => {
    if (req.multerErrorMessage) {
      return res.json({ code: -1, message: req.multerErrorMessage });
    }
    if (!req.file) {
      return res.json({ code: -1, message: "请选择文件" });
    }
    const fullUrl = `${req.protocol}://${req.get("host")}`;
    const dateFolder = dayjs().format("YYYY-MM-DD");
    return res.json({
      code: 1,
      msg: "上传成功",
      data: {
        fileUrl: `/${req.fileType}/${dateFolder}/${req.file?.filename}`,
        fullPath: `${fullUrl}/${req.fileType}/${dateFolder}/${req.file?.filename}`,
      },
    });
  },
};

module.exports = common;
